package com.jee.ssm.modules.image.controller;

import com.jee.ssm.model.Image;
import com.jee.ssm.modules.image.services.ImageService;
import com.jee.ssm.common.log.AdminControllerLog;
import com.jee.ssm.modules.ssm.controller.AdminBaseController;
import com.jee.ssm.model.json.Tip;
import com.jee.ssm.model.param.ParamMap;
import com.jee.ssm.common.utils.UUIDFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* 上传轮播图管理 Controller
* @author GaoXiang
* @version 1.0
*/
@Controller
@RequestMapping("/image")
public class ImageController extends AdminBaseController<Image> {


    /**
     * 进入上传轮播图添加页面 携带一个生成的id --> longId
     * @param model 返回的实体容器
     * @return 添加页面
     */
    @RequestMapping(value="/add")
    @RequiresPermissions("image:add")
    public String add(ModelMap model){

        model.put("longId", UUIDFactory.getStringId());
        return "manager/image/add";
    }


    /**
     * 进入上传轮播图编辑页面
     * @param model 返回上传轮播图的容器
     * @param id 上传轮播图id
     * @return 编辑页面
     */
    @RequestMapping(value="/edit")
    @RequiresPermissions("image:edit")
    public String edit(ModelMap model, @RequestParam String id) {

        model.put("data",imageService.selectById(id));
        return "manager/image/edit";
    }


    /**
     * 上传轮播图添加
     * @param image 带id的上传轮播图对象
     * @return 成功状态
     */
    @RequestMapping(value="/save")
    @ResponseBody
    @RequiresPermissions("image:add")
    @AdminControllerLog(description = "添加上传轮播图" )
    public Tip save(Image image)  {
        if (image.getUrl().equals("")){
            return new Tip(1,"请选择图片！");
        }
        try {
            imageService.insert(image);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"添加失败！");
        }

    }


    /**
     * 根据 id 修改上传轮播图
     * @param image 带id的上传轮播图对象
     * @return 成功状态
     */
    @RequestMapping(value="/update")
    @ResponseBody
    @RequiresPermissions("image:edit")
    @AdminControllerLog(description = "修改上传轮播图" )
    public Tip update(Image image) {

        try {
            imageService.updateById(image);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"修改失败！");
        }

    }


    /**
     * 根据 id 删除上传轮播图
     * @param id 上传轮播图id
     * @return 成功状态
     */
    @RequestMapping(value="/delete")
    @ResponseBody
    @RequiresPermissions("image:delete")
    @AdminControllerLog(description = "删除上传轮播图" )
    public Tip delete(@RequestParam String id) {

        String url = imageService.selectById(id).getUrl();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String realPath = request.getSession().getServletContext().getRealPath(url);
        File file = new File(realPath);
        if(file.exists()) {
            file.delete();
        }
        try {
            imageService.deleteById(id);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"删除失败！");
        }

    }


    /**
     * 根据 id 列表批量删除
     * @param ids 上传轮播图id List
     * @return 成功状态
     */
    @RequestMapping(value="/deleteByIds")
    @ResponseBody
    @RequiresPermissions("image:delete")
    @AdminControllerLog(description = "批量删除上传轮播图" )
    public Tip deleteByIds(@RequestParam("ids") List<String> ids) {
        for (String id : ids){
            String url = imageService.selectById(id).getUrl();
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String realPath = request.getSession().getServletContext().getRealPath(url);
            File file = new File(realPath);
            if(file.exists()) {
                file.delete();
            }
        }
        try {
            imageService.deleteByIds(ids);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"批量删除失败！");
        }

    }


    /**
     * 根据 id 查找上传轮播图
     * @param id 上传轮播图id
     * @return 上传轮播图对象 json
     */
    @RequestMapping(value="/findJson")
    @ResponseBody
    @RequiresPermissions("image:list")
    public Image find(@RequestParam String id) {

        return imageService.selectById(id);
    }


    /**
     * 获取上传轮播图列表 获取全部 不分页
     * @param request 请求参数
     * @return 上传轮播图列表页面
     */
    @RequestMapping(value="/all")
    @RequiresPermissions("image:list")
    public String all(HttpServletRequest request,ModelMap modelMap) {

        return list(request,modelMap,1,0);
    }


    /**
     * 获取上传轮播图列表 分页
     * @param request 请求参数
     * @param page 第几页
     * @param size 每页大小
     * @return 上传轮播图列表页面
     */
    @RequestMapping(value="/list")
    @RequiresPermissions("image:list")
    public String list(HttpServletRequest request,ModelMap modelMap,Integer page,Integer size) {

        modelMap.put("pageInfo",imageService.list(new ParamMap(request),page,size));
        modelMap.putAll(new ParamMap(request));
        return "manager/image/list";
    }

    /**
     * 图片上传
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadImage")
    @ResponseBody
    public Tip uploadImage(@RequestParam(name = "file") MultipartFile file, HttpServletRequest request) throws Exception{
        try {
            String saveUrl = request.getParameter("url");
            String filename = file.getOriginalFilename();
            String name = UUIDFactory.getStringId() + filename.substring(filename.lastIndexOf("."));
            String url = "/images/sowing/" + name;
            if(saveUrl !=null && !"".equals(saveUrl)){
                url=saveUrl+name;
            }
            String realPath = request.getSession().getServletContext().getRealPath(url);
            File img = new File(realPath);
            if (!img.exists() && !img.isDirectory()) {
                img.mkdirs();
            }
            file.transferTo(img);
            Map<String,String> map = new HashMap<>();
            map.put("url",url);
            map.put("name",filename);
            return new Tip(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(2,"上传失败！");
        }
    }

    /**
     * 删除图片
     * @param url 图片地址
     * @return
     */
    @RequestMapping(value = "/delImage")
    @ResponseBody
    public Tip delImage(String url) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String realPath = request.getSession().getServletContext().getRealPath(url);
        File file = new File(realPath);
        if(file.exists()) {
            file.delete();
        }
        return new Tip();
    }


    //---------------------------- property -------------------------------

    @Resource
    private ImageService imageService;

}
